<template>
  <div class="product-list-container">
    <!-- 搜索区 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="产品名称">
          <el-input v-model="searchForm.productName" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="产品类型" style="min-width: 180px;">
          <el-select v-model="searchForm.typeId" placeholder="请选择" clearable>
            <el-option v-for="type in typeList" :key="type.id" :label="type.categoryName" :value="type.id" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="productSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
        <el-button type="primary" @click="addProduct"><i class="el-icon-plus"></i>新增产品</el-button>
      </el-form>
    </el-card>

    <!-- 列表区 -->
    <el-card class="list-card">
      <el-table :data="productList" border stripe>
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="productName" label="产品名称" />
        <el-table-column prop="supplierId" label="供应商">
          <template #default="scope">
            {{ getSupplierName(scope.row.supplierId) }}
          </template>
        </el-table-column>
        <el-table-column prop="categoryId" label="产品类型">
          <template #default="scope">
            {{ getCategoryName(scope.row.categoryId) }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" />
        <el-table-column prop="status" label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" @click="updateProduct(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          @current-change="handlePageChange"
          :current-page="pageNum"
          :page-size="pageSize"
          :total="total"
          layout="prev, pager, next, total"
        />
      </div>
    </el-card>

    <el-dialog
      v-model="FormVisible"
      v-if="FormVisible"
      title="产品表单"
      :width="600"
      :close-on-click-modal="false"
      @close="handleDialogClose"
    >
      <ProductForm :message="currentProduct" @save-success="handleSaveSuccess" />
    </el-dialog>
  </div>
</template>

<script setup>
import { deleteProduct, getProducts, getProductTypes, searchProductsByName, searchProductsByCategoryName } from '@/api/product'
import { getProviders } from '@/api/provide'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, ref } from 'vue'
import ProductForm from './components/ProductForm.vue'

const productList = ref([])
const typeList = ref([])
const searchForm = ref({
  productName: '',
  typeId: ''
})
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const FormVisible = ref(false)
const currentProduct = ref(null)
const supplierList = ref([])

// 获取产品列表
const fetchProducts = async () => {
  try {
    let res;

    // 根据搜索条件选择不同的API
    if (searchForm.value.productName && searchForm.value.typeId) {
      // 同时有产品名称和类型ID
      // 先尝试按产品名称搜索
      res = await searchProductsByName({
        productName: searchForm.value.productName,
        pageNo: pageNum.value,
        pageSize: pageSize.value
      })
    } else if (searchForm.value.productName) {
      // 只有产品名称，使用名称搜索接口
      res = await searchProductsByName({
        productName: searchForm.value.productName,
        pageNo: pageNum.value,
        pageSize: pageSize.value
      })
    } else if (searchForm.value.typeId) {
      // 只有类型ID，需要获取类型名称后再搜索
      const categoryName = getCategoryName(searchForm.value.typeId)
      if (categoryName) {
        res = await searchProductsByCategoryName({
          categoryName: categoryName,
          pageNo: pageNum.value,
          pageSize: pageSize.value
        })
      } else {
        // 如果找不到类型名称，使用普通列表接口
        res = await getProducts({
          bo: {
            categoryId: searchForm.value.typeId
          },
          pageNo: pageNum.value,
          pageSize: pageSize.value
        })
      }
    } else {
      // 无搜索条件，使用普通列表接口
      res = await getProducts({
        bo: {},
        pageNo: pageNum.value,
        pageSize: pageSize.value
      })
    }

    // 处理响应数据
    if (res.data.records) {
      productList.value = res.data.records
      total.value = res.data.total
    } else if (Array.isArray(res.data)) {
      productList.value = res.data
      total.value = res.data.length
    } else {
      productList.value = []
      total.value = 0
    }
  } catch (error) {
    ElMessage.error('获取产品列表失败: ' + (error.message || '未知错误'))
    productList.value = []
    total.value = 0
  }
}

const addProduct = () => {
  currentProduct.value = {}
  FormVisible.value = true
}

const updateProduct = (row) => {
  currentProduct.value = { ...row }
  FormVisible.value = true
}

// 查询产品
const productSearch = () => {
  pageNum.value = 1
  fetchProducts()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    productName: '',
    typeId: ''
  }
  pageNum.value = 1
  fetchProducts()
}

// 获取所有产品类型（分页获取全部）
const fetchAllProductTypes = async () => {
  try {
    let allTypes = []
    let currentPage = 1
    let hasMore = true

    while (hasMore) {
      const res = await getProductTypes({
        pageNo: currentPage,
        pageSize: 100
      })

      allTypes = [...allTypes, ...res.data.records]

      // 检查是否还有更多数据
      if (allTypes.length >= res.data.total || res.data.records.length < 100) {
        hasMore = false
      }

      currentPage++
    }

    typeList.value = allTypes
  } catch (error) {
    ElMessage.error('获取产品类型失败: ' + (error.message || '未知错误'))
  }
}

// 获取所有供应商（分页获取全部）
const fetchAllSuppliers = async () => {
  try {
    let allSuppliers = []
    let currentPage = 1
    let hasMore = true

    while (hasMore) {
      const res = await getProviders({
        pageNo: currentPage,
        pageSize: 100
      })

      allSuppliers = [...allSuppliers, ...res.data.records]

      // 检查是否还有更多数据
      if (allSuppliers.length >= res.data.total || res.data.records.length < 100) {
        hasMore = false
      }

      currentPage++
    }

    supplierList.value = allSuppliers
  } catch (error) {
    ElMessage.error('获取供应商列表失败: ' + (error.message || '未知错误'))
  }
}

// 根据ID获取供应商名称
const getSupplierName = (supplierId) => {
  if (!supplierId) return ''
  const supplier = supplierList.value.find(item => item.id === supplierId)
  return supplier ? supplier.supplierName : ''
}

// 根据ID获取产品类型名称
const getCategoryName = (categoryId) => {
  if (!categoryId) return ''
  const category = typeList.value.find(item => item.id === categoryId)
  return category ? category.categoryName : ''
}

// 分页变化
const handlePageChange = (page) => {
  pageNum.value = page
  fetchProducts()
}

// 删除产品
const handleDelete = async (id) => {
  ElMessageBox.confirm('确认删除该产品吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteProduct(id)
      ElMessage.success('删除成功')
      fetchProducts()
    } catch (error) {
      // 特殊处理后端SQL错误
      if (error.message && error.message.includes('Unknown column')) {
        // 尝试重新获取列表，可能产品实际上已被删除
        ElMessage.warning('删除操作可能已完成，请检查列表')
        fetchProducts()
      } else {
        ElMessage.error('删除失败: ' + (error.message || '未知错误'))
      }
    }
  }).catch(() => {
    // 取消删除
  })
}

// 保存成功回调
const handleSaveSuccess = () => {
  FormVisible.value = false
  fetchProducts()
}

// 关闭对话框
const handleDialogClose = () => {
  currentProduct.value = null
}

onMounted(() => {
  fetchAllProductTypes()
  fetchAllSuppliers()
  fetchProducts()
})
</script>

<style scoped>
.list-card {
  background-color: #fff;
}

.product-list-container {
  padding: 20px;
  background-color: #f5f7fa;
  height: 100%;
  width: 100%;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}
</style>
